//
//  SearchViewController.m
//  SXH
//
//  Created by 房 国生 on 15/8/4.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "SearchViewController.h"
#import "CommonService.h"
#import "ParkEntity.h"
#import "WrapperViewController.h"
#import "IntroduceViewController.h"
#import "DBSearchManager.h"
#import "HotCityTableViewCell.h"
#import "HistorySearchTableViewCell.h"
#import "AppDelegate.h"
#import "LPUtils.h"

#define HOTKEY              @"热搜词"
#define SEARCH_HOSTORY      @"搜索历史"

@interface SearchViewController ()<UITextFieldDelegate, CitySelDelegate> {
    BOOL showRes;
}

@property (nonatomic, strong) IBOutlet UITableView *tableViewRes;
@property (nonatomic, strong) IBOutlet UIView *viewSearch;
@property (nonatomic, strong) IBOutlet UITextField *textFieldKey;
@property (nonatomic, strong) NSMutableDictionary *mutableDicSearch;
@property (nonatomic, strong) NSMutableArray *mutableArrayKeys;
@property (nonatomic, strong) NSMutableArray *mutableArrayResult;
@end

@implementation SearchViewController
@synthesize viewSearch, textFieldKey, tableViewRes;
@synthesize mutableArrayKeys, mutableArrayResult, mutableDicSearch;
@synthesize wrapperMainVC;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initNavigateionBar];
    showRes = NO;
    
    mutableArrayResult = [[NSMutableArray alloc] init];
    
    mutableArrayKeys = [[NSMutableArray alloc]initWithObjects:SEARCH_HOSTORY, nil];
    
    NSMutableArray *arrayRes = [DBSearchManager selectAllSearchRes];
    
    if ([arrayRes count] > 0) {
        ParkEntity *entity = [[ParkEntity alloc] init];
        entity.title = @"";
        [arrayRes addObject:entity];
    }
    
    mutableDicSearch = [[NSMutableDictionary alloc] init];
    [mutableDicSearch setValue:arrayRes forKey:[mutableArrayKeys objectAtIndex:0]];
    
    [self getHotSearch];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self keyboardHide];
}

- (void)keyboardHide {
    [textFieldKey resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark Table view data source

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    bgView.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.95 alpha:1];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 0, 250, 30)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor darkGrayColor];
    titleLabel.font = [UIFont systemFontOfSize:13];
    
    NSString *key = [mutableArrayKeys objectAtIndex:section];
    titleLabel.text = key;
    
    [bgView addSubview:titleLabel];
    
    return bgView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    if (showRes == YES) {
        return 1;
    } else {
        return [mutableArrayKeys count];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (showRes == YES) {
        return [mutableArrayResult count];
    } else {
        NSString *key = [mutableArrayKeys objectAtIndex:section];
        NSArray *citySection = [mutableDicSearch objectForKey:key];
        
        if ([key isEqualToString:HOTKEY] == YES) {
            return [citySection count]/3 + ([citySection count]%3 > 0 ? 1 : 0);
        } else {
            return [citySection count];
        }
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (showRes == YES) {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
            cell.backgroundColor = [UIColor clearColor];
            cell.contentView.backgroundColor = [UIColor whiteColor];
            //cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.textLabel setTextColor:[UIColor blackColor]];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
        }
        
        ParkEntity *parkEntity = [mutableArrayResult objectAtIndex:indexPath.row];
        
        cell.textLabel.text = parkEntity.title;
        
        return cell;
    } else {
        NSString *key = [mutableArrayKeys objectAtIndex:indexPath.section];
        
        if ([key isEqualToString:HOTKEY] == YES) {
            static NSString *couponTableViewCellIdentifier=@"HotCityTableViewCell";
            HotCityTableViewCell *cell = (HotCityTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
            if (cell == nil) {
                NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"HotCityTableViewCell" owner:self options:nil];
                cell = [array objectAtIndex:0];
                cell.delegate = self;
            }
            
            NSArray *hotSearchSection = [mutableDicSearch objectForKey:key];
            //
            if (indexPath.row*3 < [hotSearchSection count]) {
                NSString *entity = [hotSearchSection objectAtIndex:indexPath.row*3];
                
                [cell.btnLeft setTitle:entity forState:UIControlStateNormal];
                cell.btnLeft.tag = indexPath.row*3;
                cell.btnLeft.hidden = NO;
                [LPUtils setButtonStyle:cell.btnLeft];
            }
            
            if (indexPath.row*3 + 1 < [hotSearchSection count]) {
                NSString *entity = [hotSearchSection objectAtIndex:indexPath.row*3 + 1];
                
                [cell.btnMiddle setTitle:entity forState:UIControlStateNormal];
                cell.btnMiddle.tag = indexPath.row*3 + 1;
                cell.btnMiddle.hidden = NO;
                [LPUtils setButtonStyle:cell.btnMiddle];
            }
            
            if (indexPath.row*3 + 2 < [hotSearchSection count]) {
                NSString *entity = [hotSearchSection objectAtIndex:indexPath.row*3 + 2];
                
                [cell.btnRight setTitle:entity forState:UIControlStateNormal];
                cell.btnRight.tag = indexPath.row*3 + 2;
                cell.btnRight.hidden = NO;
                [LPUtils setButtonStyle:cell.btnRight];
            }
            return cell;
        } else {
            static NSString *CellIdentifier = @"HistorySearchTableViewCell";
            HistorySearchTableViewCell *cell = (HistorySearchTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"HistorySearchTableViewCell" owner:self options:nil];
                cell = [array objectAtIndex:0];
            }
            NSArray *hotSearchSection = [mutableDicSearch objectForKey:key];
            
            if (indexPath.row == [hotSearchSection count] -1) {
                cell.labelTitle.hidden = YES;
                cell.imageViewSearch.hidden = YES;
            } else {
                cell.labelRemove.hidden = YES;
                cell.imageViewRemove.hidden = YES;
                
                ParkEntity *searchKey = [hotSearchSection objectAtIndex:indexPath.row];
                cell.labelTitle.text = searchKey.title;
            }
            return cell;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (showRes == YES) {
        ParkEntity *entity = [mutableArrayResult objectAtIndex:indexPath.row];
        [self.navigationController popViewControllerAnimated:NO];
        
        if ([entity.is_business isEqualToString:@"0"] == YES) {
            IntroduceViewController *vc = [[IntroduceViewController alloc] init];
            vc.parkId = [NSString stringWithFormat:@"%@",entity.ID];
            [wrapperMainVC.navigationController pushViewController:vc animated:YES];
        } else {
            WrapperViewController *vc = [[WrapperViewController alloc] init];
            vc.parkEntity = entity;
            
            [wrapperMainVC.navigationController pushViewController:vc animated:YES];
        }
        
        [DBSearchManager createTable];
//        [DBSearchManager saveOrUpdataEntity:entity.ID Name:entity.title];
        [DBSearchManager saveOrUpdataEntity:entity.ID Name:entity.title andIsBussiness:entity.is_business];
        
        //历史记录需要加一
        NSMutableArray *hotSearchSection = [mutableDicSearch objectForKey:SEARCH_HOSTORY];
        if ([hotSearchSection count]== 0) {
            ParkEntity *entity = [[ParkEntity alloc] init];
            entity.title = @"";
            [hotSearchSection addObject:entity];
        } else {
            [hotSearchSection insertObject:entity atIndex:[hotSearchSection count]-1];
        }
        [tableViewRes reloadData];
    } else {
        NSString *key = [mutableArrayKeys objectAtIndex:indexPath.section];
        if ([key isEqualToString:SEARCH_HOSTORY] == YES) {
            NSMutableArray *hotSearchSection = [mutableDicSearch objectForKey:key];
            if (indexPath.row == [hotSearchSection count] - 1) {
                [hotSearchSection removeAllObjects];
                [DBSearchManager deleteDataBase];
                [tableViewRes reloadData];
            }else{
                NSMutableArray *hotSearchSection = [mutableDicSearch objectForKey:SEARCH_HOSTORY];
                ParkEntity *entity = [hotSearchSection objectAtIndex:indexPath.row];
                [self.navigationController popViewControllerAnimated:NO];
                
                if ([entity.is_business isEqualToString:@"0"] == YES) {
                    IntroduceViewController *vc = [[IntroduceViewController alloc] init];
                    vc.parkId = [NSString stringWithFormat:@"%@",entity.ID];
                    [wrapperMainVC.navigationController pushViewController:vc animated:YES];
                } else {
                    WrapperViewController *vc = [[WrapperViewController alloc] init];
                    vc.parkEntity = entity;
                    [wrapperMainVC.navigationController pushViewController:vc animated:YES];
                }
            }
        }
    }
}

- (void) initNavigateionBar {
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
        // Load resources for iOS 6.1 or earlier
        self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.56 green:0.76 blue:0.12 alpha:1];
    } else {
        // Load resources for iOS 7 or later
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.56 green:0.76 blue:0.12 alpha:1];
    }
    
    //导航条的搜索条
    [viewSearch.layer setMasksToBounds:YES];
    [viewSearch.layer setCornerRadius:6.0]; //设置矩形四个圆角半径
    self.navigationItem.titleView = viewSearch;
    
    UIButton *btnBlank =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    UIBarButtonItem *nextButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnBlank];
    self.navigationItem.rightBarButtonItem = nextButtonItem;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textFieldKey.text.length > 0) {
        [self searchParkData];
        showRes = YES;
    }
    
    [textFieldKey resignFirstResponder];
    return YES;
}

- (IBAction)doSearchAction:(id)sender {
    if (textFieldKey.text.length > 0) {
        [self searchParkData];
        showRes = YES;
    }
}

- (void)cityButtonAction:(NSInteger)tag {
    NSArray *hotSearchSection = [mutableDicSearch objectForKey:HOTKEY];
    NSString *hotKey = [hotSearchSection objectAtIndex:tag];
    
    textFieldKey.text = hotKey;
    if (textFieldKey.text.length > 0) {
        [self searchParkData];
        showRes = YES;
    }
}

- (void) searchParkData {
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           textFieldKey.text, @"title",nil];
    
    [service getNetWorkData:param
                       Path:PARKPATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      NSArray *array = [dic objectForKey:@"rows"];
                      
                      [mutableArrayResult removeAllObjects];
                      
                      for (NSDictionary* attributes in array) {
                          ParkEntity *parkEntity = [[ParkEntity alloc] init];
                          parkEntity = [parkEntity initWithAttributes:attributes];
                          [mutableArrayResult addObject:parkEntity];
                      }
                      
                      [tableViewRes reloadData];
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}

- (void) getHotSearch {
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           @"", @"version",nil];
    
    [service getNetWorkData:param
                       Path:HOT_SEARCH_KEY
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      
                      [mutableArrayKeys insertObject:HOTKEY atIndex:0];
                      [mutableDicSearch setValue:array forKey:HOTKEY];
                      
                      [tableViewRes reloadData];
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"SearchViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"SearchViewController"];
}
@end
